<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data1: { type: Object as () => any, required: true },
    data2: { type: Object as () => any, default: [] },
    data3: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    dataName: { type: Object as () => any, default: [] },
    title: { type: String, default: '' },
    markLine1: { type: Number, default: 0 },
    markLine2: { type: Number, default: 0 },
    markLine3: { type: Number, default: 0 },
    markLine4: { type: Number, default: 0 },
    isScale: { type: Boolean, default: false },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref<any>({
    legend: {
      data: props.dataName,
      top: props.title == '' ? '0%' : '12%', // 图例位置
    },
    tooltip: {
      trigger: 'item',
      appendToBody: true, // 关键设置
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true, // 让 grid 包含坐标轴文本
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      axisTick: { show: false },
    },
    yAxis: {
      type: 'value',
      // name: props.dataName[0] || '',
      splitLine: { show: false },
      scale: props.isScale,
    },
    series: [
      {
        name: props.dataName[0],
        type: 'line',
        itemStyle: {
          color: '#5470c6',
        },
        data: props.data1,
        smooth: false,
      },
    ],
  });

  const initCharts = () => {
    try {
      option.value.series[0].data = props.data1 ?? [];
      if (props.data2.length > 0) {
        option.value.series.push({
          name: props.dataName[1],
          type: 'line',
          itemStyle: {
            color: '#fac858', // 使用橙色表示实际
          },
          data: props.data2,
          smooth: false,
        });
      }
      if (props.data3.length > 0) {
        option.value.series.push({
          name: props.dataName[2],
          type: 'line',
          data: props.data3,
          itemStyle: {
            color: '#91cc75',
          },
          smooth: false,
        });
      }
      // 统一构建 markLine 数据，避免变量遮蔽导致丢失
      const seriesColorData1 = '#5470c6';
      const seriesColorData2 = '#fac858';
      const markLineData: any[] = [];
      if (props.markLine1 && props.markLine1 !== 0) {
        markLineData.push({
          name: '上限',
          yAxis: props.markLine1,
          label: { formatter: '上限', color: seriesColorData1 },
          lineStyle: { color: seriesColorData1, width: 1 },
        });
        if (props.markLine2 && props.markLine2 !== 0) {
          markLineData.push({
            yAxis: props.markLine2,
            label: { formatter: '下限', color: seriesColorData1 },
            lineStyle: { color: seriesColorData1, width: 1 },
          });
        }
      }
      if (props.markLine3 && props.markLine3 !== 0) {
        markLineData.push({
          yAxis: props.markLine3,
          label: { formatter: '上限', color: seriesColorData2 },
          lineStyle: { color: seriesColorData2, width: 1 },
        });
        if (props.markLine4 && props.markLine4 !== 0) {
          markLineData.push({
            yAxis: props.markLine4,
            label: { formatter: '下限', color: seriesColorData2 },
            lineStyle: { color: seriesColorData2, width: 1 },
          });
        }
      }
      if (markLineData.length > 0) {
        option.value.series[0].markLine = {
          symbol: 'none',
          data: markLineData,
        } as any;

        // 当有标记线时，手动设置Y轴范围以保持空隙
        const allMarkValues = markLineData.map((item) => item.yAxis).filter((val) => val !== undefined);
        const allDataValues = [...(props.data1 || []), ...(props.data2 || []), ...(props.data3 || [])];

        if (allMarkValues.length > 0 && allDataValues.length > 0) {
          const minMark = Math.min(...allMarkValues);
          const maxMark = Math.max(...allMarkValues);
          const minData = Math.min(...allDataValues);
          const maxData = Math.max(...allDataValues);

          // 设置Y轴范围，在标记线和数据之间留出空隙
          const padding = Math.max((maxMark - minMark) * 0.1, (maxData - minData) * 0.1);
          option.value.yAxis.min = Math.min(minMark, minData) - padding;
          option.value.yAxis.max = Math.max(maxMark, maxData) + padding;
        }
      }
      option.value.xAxis.data = props.datax ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    option.value.series[0].data = props.data1 ?? [];
    if (props.data2.length > 0) {
      option.value.series.push({
        name: props.dataName[1],
        type: 'bar',
        itemStyle: {
          color: '#fac858', // 使用橙色表示实际
        },
        data: props.data2,
        smooth: false,
      });
    }
    if (props.data3.length > 0) {
      option.value.series.push({
        name: props.dataName[2],
        type: 'bar',
        data: props.data3,
        itemStyle: {
          color: '#91cc75',
        },
        smooth: false,
      });
    }
    // 同步 markLine 到更新逻辑
    const seriesColorData1 = '#5470c6';
    const seriesColorData2 = '#fac858';
    const markLineData: any[] = [];
    if (props.markLine1 && props.markLine1 !== 0) {
      markLineData.push({
        yAxis: props.markLine1,
        label: { formatter: '上限', color: seriesColorData1 },
        lineStyle: { color: seriesColorData1, width: 1 },
      });
      if (props.markLine2 && props.markLine2 !== 0) {
        markLineData.push({
          yAxis: props.markLine2,
          label: { formatter: '下限', color: seriesColorData1 },
          lineStyle: { color: seriesColorData1, width: 1 },
        });
      }
    }
    if (props.markLine3 && props.markLine3 !== 0) {
      markLineData.push({
        yAxis: props.markLine3,
        label: { formatter: '上限', color: seriesColorData2 },
        lineStyle: { color: seriesColorData2, width: 1 },
      });
      if (props.markLine4 && props.markLine4 !== 0) {
        markLineData.push({
          yAxis: props.markLine4,
          label: { formatter: '下限', color: seriesColorData2 },
          lineStyle: { color: seriesColorData2, width: 1 },
        });
      }
    }
    if (markLineData.length > 0) {
      option.value.series[0].markLine = { symbol: 'none', data: markLineData } as any;
    } else {
      // 清理已有 markLine 避免残留
      if (option.value.series[0].markLine) delete option.value.series[0].markLine;
    }
    option.value.xAxis.data = props.datax ?? [];
    chartInstance?.setOption(option.value, true);
    chartInstance?.resize();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', () => chartInstance?.resize());
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.data1],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
